import { initExecute, check } from '../../utils/index.js';
export default function(hook, { Spin, Midder, fieldText, fieldProp, ProPager, ProTable }) {
	return {
		isJiess: true,
		name: 'JiessTable',
		setup({
			datas,
			items,
			create,
			mounte,
			update,
			render,
			primaryKey,
			tableProps,
			pagerProps,
			itemsParam,
			types = ['add', 'edit', 'filter'],
		}) {
			const { $reactive, $jiess } = hook.$m;
			// ===================create========================
			// 关闭中介者的单列缓存模式
			const midder = new(Midder.default || Midder)($jiess(), 'JiessTableMidder', 'no-store');
			const execFunc = initExecute.call(this, midder);
			midder.ctx = this;
			midder.types = types;
			midder.pager = {
				values: {},
				pagerProps: execFunc(pagerProps)
			};
			midder.table = {
				tableProps: execFunc(tableProps),
				// 用于存放静态数据
				values: {},
				// 列表的row-key
				primaryKey: 'id',
				// 应对react的严格模式
				reload: () => {}
			};
			// 初始化注入初始数据
			types.forEach((type) => {
				midder[type] = midder[type] || {};
				midder[type].items = {};
				midder[type].values = {};
				midder[type].httpParam = {};
				// 用于存放所有的表单操作对象
				midder[type].actions = [];
			});
			// =====================================
			midder.proxy = $reactive({
				total: 0,
				pageSize: 10,
				currentPage: 1,
				pageSizes: [10, 20, 30, 40, 50, 100],
				columns: [],
				datas,
			});
			// ------------------------------------------
			const initColumns = (items) => {
				const columns = [];
				if (Array.isArray(items)) {
					items.forEach(({
						key,
						prop,
						text,
						renderItem,
						// 表头项是否显示
						useInTable = true,
						...other
					}) => {
						useInTable && columns.push({
							key: key || prop || text,
							[fieldText]: text,
							[fieldProp]: prop,
							...other
						});
						// 根据类型轮流注入渲染函数
						types.forEach((type) => {
							const v = renderItem?.call(this, type, prop, text);
							const { items } = midder[type];
							if (check(v, 'BuildItem')) {
								items[prop] = (area) => v.useArea(area);
							}
							typeof v === 'function' && (items[prop] = v);
						});
					});
				};
				midder.proxy.columns = columns;
			}
			// ===================create========================
			if (typeof create === 'function') create?.call(this, midder);
			// items与container谁先执行，待验证
			if (typeof items === 'function') {
				// items与渲染同步加载，所以不能定义为异步函数
				initColumns(items.call(this, midder, itemsParam));
			} else {
				initColumns(items);
			}
			const table = { is: ProTable, midder, update, primaryKey };
			const pager = ProPager && { is: ProPager, midder };
			// ===================render========================
			render.call(this, midder, { table, pager });
			// ===================mounte========================
			if (typeof mounte === 'function') setTimeout(() => mounte.call(this, midder));
		},
	};
}